<template>
  <view>
    <u-popup mode="right" round="5rpx" :show="show" @close="close">
      <view class="popup-content p-10rpx">
        <view class="text-center p-10rpx">打印预览</view>
        <view class="report-content p-10rpx" id="render-report" >
          <text class="title">{{ businessInfo.businessName }}</text>
          <text class="sub-title">【营收统计报表】</text>
          <view>
            <view>统计日期: {{ queryParams.startDate }}</view>
            <view>打印日期: {{ dayjs().format("YYYY-MM-DD HH:mm:ss") }}</view>
            <view>打印人: {{ userInfo.name }}</view>
          </view>

          <view class="item-box">
            <view class="btitle">收款统计</view>
            <u-row gutter="0">
              <u-col span="4"><text class="line-text">收款业务</text></u-col>
              <u-col span="4"><text class="line-text">收款笔数</text></u-col>
              <u-col span="4"><text class="line-text">收款金额</text></u-col>
            </u-row>
            <u-row gutter="0" v-for="(item, index) in dataList.collectionStatistics" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}笔</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">收款构成</view>
            <u-row gutter="0">
              <u-col span="4"><text class="line-text">收款方式</text></u-col>
              <u-col span="4"><text class="line-text">收款笔数</text></u-col>
              <u-col span="4"><text class="line-text">收款金额</text></u-col>
            </u-row>
            <u-row gutter="0" v-for="(item, index) in dataList.collectionComposition" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}笔</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">收款构成-营业收入</view>
            <u-row gutter="0">
              <u-col span="4"><text class="line-text">收款方式</text></u-col>
              <u-col span="4"><text class="line-text">收款笔数</text></u-col>
              <u-col span="4"><text class="line-text">收款金额</text></u-col>
            </u-row>
            <u-row gutter="0" v-for="(item, index) in dataList.operatingRevenue" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}笔</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">收款构成-会员业务</view>
            <u-row gutter="0">
              <u-col span="4"><text class="line-text">收款方式</text></u-col>
              <u-col span="4"><text class="line-text">收款笔数</text></u-col>
              <u-col span="4"><text class="line-text">收款金额</text></u-col>
            </u-row>
            <u-row gutter="0" v-for="(item, index) in dataList.memberPayment" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}笔</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">会员消费</view>
            <u-row gutter="0" v-for="(item, index) in dataList.memberConsumption" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}笔</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">会员充值</view>
            <u-row gutter="0" v-for="(item, index) in dataList.memberRecharge" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}笔</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">会员卡押金</view>
            <u-row gutter="0">
              <u-col span="4"><text class="line-text">类型</text></u-col>
              <u-col span="4"><text class="line-text">张数</text></u-col>
              <u-col span="4"><text class="line-text">金额</text></u-col>
            </u-row>
            <u-row gutter="0" v-for="(item, index) in dataList.membershipCardDeposit" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}张</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">订单统计</view>
            <u-row gutter="0" v-for="(item, index) in dataList.orderStatistics" :key="index">
              <u-col span="6">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="6"
                ><text class="line-text">{{ item.num }}笔</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">敏感操作统计</view>
            <u-row gutter="0">
              <u-col span="4"><text class="line-text">项目</text></u-col>
              <u-col span="4"><text class="line-text">数量</text></u-col>
              <u-col span="4"><text class="line-text">金额</text></u-col>
            </u-row>
            <u-row gutter="0" v-for="(item, index) in dataList.refundStatistics" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}单</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="item-box">
            <view class="btitle">优惠统计</view>
            <u-row gutter="0">
              <u-col span="4"><text class="line-text">优惠方式</text></u-col>
              <u-col span="4"><text class="line-text">单数</text></u-col>
              <u-col span="4"><text class="line-text">优惠金额</text></u-col>
            </u-row>
            <u-row gutter="0" v-for="(item, index) in dataList.discountStatistics" :key="index">
              <u-col span="4">
                <text class="line-text">{{ item.name }}</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.num }}单</text></u-col
              >
              <u-col span="4"
                ><text class="line-text">{{ item.money }}</text></u-col
              >
            </u-row>
          </view>

          <view class="my-2">
            <view class="my-2 flex">
              <text class="whitespace-nowrap">统计人签字: </text>
              <view class="line-empty"></view>
            </view>
            <view class="my-2 flex">
              <text class="whitespace-nowrap">监督人签字: </text>
              <view class="line-empty"></view>
            </view>
          </view>

          <view class="my-2">
            <text class="block my-2 font-bold">提示: </text>
            <text>1. 如统计后存在取消订单的情况，核对时请以营收报表的数据为准。 </text>
          </view>
        </view>

        <view class="w-50rpx m-auto mt-8rpx">
          <!-- @click="startPrint(canvasToImage)" -->
          <!-- @click="canvasToImage.generateImage" -->
          <u-button
            @click="startPrint"
            :loading="pageStatus.loading"
            icon-color="white"
            :disabled="pageStatus.loading"
            type="primary"
            >打印</u-button
          >
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from "vue";
import { revenueReportPreview } from "@/api";
import { useStore } from "vuex";
import dayjs from "dayjs";
import H5PlusPlugin from "@/king-components/js/KingonPlus";


const pageStatus = reactive({
  loading: true,
});

const store = useStore();
const userInfo = store.getters.userInfo;
const businessInfo = store.getters.businessInfo;

const queryParams = ref({});

const show = ref(false);
const open = (data) => {
  if (data) {
    queryParams.value = {
      ...data,
    };
  }
  getData(true);
  show.value = true;
};
const close = () => {
  // 关闭
  show.value = false;
};

defineExpose({
  open,
  close,
});

// 加载数据
const dataList = ref({});
const getData = async () => {
  // uni.showLoading({ title: "加载中", mask: true });
  try {
    const { data, success } = await revenueReportPreview(queryParams.value);
    // if (!success) throw Error("获取数据失败");
    dataList.value = data;

    uni.hideLoading();
    pageStatus.loading = false;
  } catch (error) {
    console.error("获取数据失败#", error);
    uni.hideLoading();
    uni.showToast({
      title: error?.data?.msg || "获取数据失败",
      icon: "none",
    });
  }
};

const imgIsOk = (data) => {
  console.log("imgIsOk", data);
};

const startPrint = async () => {
  try {
    pageStatus.loading = true;

    try {
      // 生成图片
      const result = await generateImage();
      console.log("生成图片成功#", result);
    } catch (error) {
      console.error("生成图片失败#", error);
    }

    // 初始化打印机器
    H5PlusPlugin.execFunction("HnXfjPrinterInit", "{}", () => {
      // 打印
      const Arg = [];
      // 将打印预览数据转换为base64格式

      H5PlusPlugin.execFunction(
        "HnXfjPrinte",
        Arg,
        function (result) {
          //参数用例，{"MsgType":"1""HRValue":102"SystolicValue":129"DiastolicValue":97}，心率：HRValue，收缩压：SystolicValue，舒张压：DiastolicValue
          plus.nativeUI.alert(result);
        },
        function (result) {
          plus.nativeUI.alert(result);
        }
      );
    });
  } catch (error) {
    console.error("打印失败#", error);
    pageStatus.loading = false;
  }
};

const reportPreview = reactive({
  posterUrl: "",
});

// 生成图片需要调用的方法
const generateImage = () => {
  return new Promise((resolve, reject) => {
    uni.showLoading({ title: "生成中", mask: true });
    const timer = setTimeout(() => {
      const dom = uni.createSelectorQuery().select("#report-content");
      // const dom = document.getElementById("report-content"); // 需要生成图片内容的 dom 节点
      html2canvas(dom, {
        width: dom.clientWidth, //dom 原始宽度
        height: dom.clientHeight,
        scrollY: 0, // html2canvas默认绘制视图内的页面，需要把scrollY，scrollX设置为0
        scrollX: 0,
        useCORS: true, //支持跨域
        // scale: 2, // 设置生成图片的像素比例，默认是1，如果生成的图片模糊的话可以开启该配置项
      })
        .then((canvas) => {
          // 生成成功
          // html2canvas 生成成功的图片链接需要转成 base64位的url
          receiveRenderData(canvas.toDataURL("image/png"));
          resolve({ success: true, data: reportPreview });
        })
        .catch((err) => {
          console.error("html2canvas 生成失败", err);
          // 生成失败 弹出提示弹窗
          uni.hideLoading();
          uni.showToast({ title: "生成失败", icon: "none" });
          reject({ success: false, data: null });
        })
        .finally(() => {
          clearTimeout(timer);
        });
    }, 300);
  });
};

const receiveRenderData = (val) => {
  reportPreview.posterUrl = val.replace(/[\r\n]/g, ""); // 去除base64位中的空格
};
</script>
<style scoped lang="scss">
.popup-content {
  max-width: 350px;
  width: 350px;
  position: relative;
  box-sizing: border-box;
  overflow: scroll;
  height: 100%;

  .title {
    font-weight: bold;
  }

  .textarea {
    width: 80%;
    margin: 10rpx 0rpx;

    ::v-deep .u-textarea__field {
      font-size: 13rpx;
    }
  }
}

.report-content {
  /** 这里固定px */

  width: 300px;
  background-color: rgb(240, 240, 240);
  box-sizing: border-box;
  margin: 0 auto;
  font-size: 16px;
  line-height: 22px;
  display: flex;
  flex-direction: column;
  padding: 20px;

  .title {
    font-size: 12rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
  }

  .sub-title {
    text-align: center;
    margin-bottom: 20px;
  }

  .item-box {
    display: flex;
    flex-direction: column;
    border: 1px dashed #000;
    margin-top: 10px;
    border-radius: 5px;
    padding: 20px 10px;
    margin-bottom: 20px;

    .btitle {
      font-weight: bold;
      text-align: center;
      margin-bottom: 5px;
    }

    .line-text {
      display: block;
      text-align: center;
      margin-top: 5px;
    }
  }

  .line-empty {
    border-bottom: 1px solid#000;
    width: 100%;
    box-sizing: border-box;
    margin-left: 10px;
  }
}
</style>
